import request from '@/utils/request'
var baseMixin = {
  data() {
    return {
      roleMark: localStorage.getItem('mark') || "",
      userId: localStorage.getItem('userId') || "",
      orgId: localStorage.getItem('orgId') || "",
      orgName: localStorage.getItem('orgName') || "",
      tableKey: 0,
      listLoading: false,
      list: [],
      listQuery: {
        pageIndex: 1,
        pageSize: 10,
        condition: {},
        orderBy: [{
          desc: true,
          orderBy: 'createTime'
        }]
      },
      baseParam: {
        isLeaf: 1
      },
      headerCellStyle: {
        background: '#f7f8f9',
        color: '#666'
      },
      Urls: {
        listUrl: '',
        delUrl: '',
        dictTypeUrl: '/biz/api/dict/typeList',
        dictChildrenUrl: '/biz/api/dict/typeList',
        batchDelUrl: '',
        downloadExcelUrl: '',
        printPdfUrl: '',
        exportExcelUrl: '',
        importExcelUrl: '',
        areaListUrl: '/auth/api/area/children/',
        fileIdsUrl: '',
        batchFileIdsUrl: '',
        downloadFileUrl: '/file/api/file/batchDownload',
      },
      total: 0,
      sortOptions: [],
      multipleSelection: [],
      downloadLoading: false,
      importLoading: false,
      fileExt: '.xls',
      pickerOptionsStart: {
        disabledDate: time => {
          let endDateVal = this.listQuery.condition.endTime;
          if (endDateVal) {
            return time.getTime() > new Date(endDateVal).getTime();
          }
        }
      },
      pickerOptionsEnd: {
        disabledDate: time => {
          let beginDateVal = this.listQuery.condition.startTime;
          if (beginDateVal) {
            return (
              time.getTime() <
              new Date(beginDateVal).getTime() - 1 * 24 * 60 * 60 * 1000
            );
          }
        }
      }
    }
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange,
        type: 'radio'
      }
    }
  },
  watch: {
    'pagination.current'(val) {
      this.selectedRowKeys = []
      this.selectionRows = []
    }
  },
  filters: {
    amountFilter: (val) => {
      if (!val) {
        return 0
      }
      return parseFloat((val / 100).toFixed(2))
    },
    // 格式化金额-万元
    filterMoney(value) {
      return (value || 0) && parseFloat((value / 10000).toFixed(2))
    }
  },
  created() {},
  mounted() {},
  methods: {
    //获取表格序号
    getIndex($index) {
      return (this.listQuery.pageIndex - 1) * this.listQuery.pageSize + $index + 1
    },
    // 新增表单
    handleCreate() {
      this.$refs["tableForm"].dialogStatus = "create";
      this.$refs["tableForm"].add()
    },
    // 编辑表单
    handleUpdate(row) {
      this.$refs["tableForm"].dialogStatus = "update";
      this.$refs["tableForm"].edit(row)
    },
    // 表单完成后
    afterSubmit() {
      this.getList(1)
    },
    // 删除数据
    handleDelete(row) {
      var that = this
      let id = row.id
      this.$confirm('此操作将永久删除该条数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request({
          url: that.Urls.delUrl + id,
          method: 'get'
        }).then(res => {
          if (res.code == 0) {
            that.$notify.success({
              message: '删除成功'
            })
            that.afterSubmit()
          } else {
            that.$notify.error({
              message: res.msg
            })
          }
        })
      }).catch(() => {});
    },
    // 多选
    handleSelectionChange(val) {
      console.log('selection', val)
      this.multipleSelection = val;
    },
    // 加载列表数据-分页
    getList(arg) {
      if (arg === 1) {
        this.listQuery.pageIndex = 1;
      };
      this.listQuery.condition = Object.assign({}, this.baseParam, this.listQuery.condition)
      this.listLoading = true;
      request({
        url: this.Urls.listUrl,
        method: 'post',
        data: this.listQuery
      }).then(res => {
        this.listLoading = false
        if (res.code == 0) {
          this.total = res.data.total;
          this.list = res.data.list || [];
        } else {
          this.$notify.error({
            message: res.msg
          })
        }
      }).catch(() => {
        this.listLoading = false;
      })
    },
    refreshTable() {
      this.tableShow = false
      this.$nextTick(() => {
        this.tableShow = true
      })
    },
    // 根据已展开的行查询数据（用于保存后刷新时异步加载子级的数据）
    loadDataByExpandedRows(dataList) {
      let id = this.expandedRowKeys[0]
      if (this.expandedRowKeys.length > 0) {
        request({
          url: this.Urls.subListUrl + id,
          method: 'get'
        }).then(res => {
          if (res.code == 0) {
            let childrenMap = res.data.records
            let fn = (list) => {
              list.forEach(data => {
                if (this.expandedRowKeys.includes(data.id)) {
                  data.children = childrenMap
                  fn(data.children)
                }
              })
            }
            fn(dataList)
          } else {
            this.$notify.error({
              message: res.msg
            })
          }
        })
      }
    },
    // 点击展开树图标
    handleExpand(expanded, record) {
      // this.expandedRowKeys[0] = record.id
      // 判断是否是展开状态
      if (expanded) {
        // 判断子级的首个项的标记是否是“正在加载中”，如果是就加载数据
        if (record.children[0].isLoading === true) {
          const id = record.id
          const data = this.list
          request({
            url: this.Urls.subListUrl + record.id,
            method: 'get'
          }).then(res => {
            if (res.code == 0) {
              const children = res.data.records || []
              const dataMap = (items) => {
                items.find((item) => {
                  if (item.id === id) {
                    item.children = children
                    for (let i = 0; i < item.children.length; i++) {
                      if (item.children[i].isLeaf == 0) {
                        let loadChild = {
                          id: `${item.children[i].id}_loadChild`,
                          name: 'loading...',
                          isLoading: true
                        }
                        item.children[i].children = [loadChild]
                      }
                    }
                    return items
                  }
                  if (item.children && item.children.length > 0) {
                    dataMap(item.children)
                  }
                })
              }
              dataMap(data || [])
            } else {
              this.$notify.error({
                message: res.msg
              })
            }
          })
        }
      }
    },
    // 搜索查询
    handleSearch() {
      console.log('search param...', this.listQuery.condition)
      this.listQuery.condition.parentId = undefined;
      this.getList(1);
      this.afterSearch();
    },
    // 搜索重置
    resetSearch() {
      this.listQuery.condition = {};
      this.getList(1);
      this.afterSearch();
    },
    afterSearch() {},
    // 加载列表数据-无分页
    getData() {
      this.localLoading = true
      request({
        url: this.Urls.listUrl,
        method: 'get'
      }).then(res => {
        this.localLoading = false
        if (res.code == 0) {
          this.list = res.data.records || [];
        } else {
          this.$notify.error({
            message: res.msg
          })
        }
      })
    },
    // 改变页码
    onChangePage(page, pageSize) {
      this.pagination.current = page;
      this.pagination.pageSize = pageSize;
      this.getList();
    },
    // 改变分页条数
    onShowSizeChange(page, pageSize) {
      this.pagination.current = page;
      this.pagination.pageSize = pageSize;
      this.getList();
    },
    // 表格字段排序
    handleTableChange(pagination, filters, sorter) {
      if (Object.keys(sorter).length > 0) {
        this.listQuery.orderBy[0].desc = (sorter.order == 'ascend') ? false : true
        this.listQuery.orderBy[0].orderBy = sorter.field
      };
      this.pagination = pagination;
      this.getList();
    },
    sortChange(data) {
      const {
        prop,
        order
      } = data;
      if (prop === "id") {
        this.sortByID(order);
      }
    },
    // 搜索栏展开
    toggleAdvanced() {
      this.advanced = !this.advanced
    },

    // table勾选时
    onSelectChange(selectedRowKeys, selectionRows) {
      console.log(selectedRowKeys, selectionRows)
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    },
    // 全选
    allSelect() {
      this.selectedRowKeys = this.list.map(item => {
        return item.id
      })
    },
    // 反选
    reverseSelect() {
      let newArr = this.list.filter(item => !this.selectedRowKeys.some(ele => ele === item.id))
      this.selectedRowKeys = newArr.map(item => item.id)
    },

    // 获取一级字典数据
    getDictData(type, data) {
      request({
        url: this.Urls.dictTypeUrl,
        method: 'get',
        params: {
          type: type
        }
      }).then(res => {
        if (res.code == 0) {
          this[data] = res.data.records;
        } else {
          this.$notify.error({
            message: res.msg
          })
        }
      })
    },
    // 添加子级
    handleAddSub() {
      if (this.selectedRowKeys.length == 0) {
        this.$message.warning('请选择你要进行该操作的数据!');
        return false
      }
      this.$refs.modalForm.dialogStatus = 'add'
      this.$refs.modalForm.isDisabled = true
      this.$refs.modalForm.edit({
        'parentId': this.selectionRows[0].id
      });
    },
    // 批量删除
    handleBatchDel() {
      var _this = this
      _this.$confirm({
        title: '确定要删除您选择的数据？',
        content: '删除不可恢复',
        okType: 'danger',
        onOk() {
          request({
            url: _this.Urls.batchDelUrl,
            method: 'post',
            data: {
              ids: _this.selectedRowKeys
            }
          }).then(res => {
            if (res.code == 0) {
              _this.$notify.success({
                message: '删除成功'
              })
              _this.afterSubmit()
            } else {
              _this.$notify.error({
                message: res.msg
              })
            }
          })
        },
        class: 'test'
      })
    },
    // 表单详情
    handleDetail() {
      if (this.selectedRowKeys.length == 0) {
        this.$message.warning('请选择你要进行该操作的数据!');
        return false
      }
      this.$refs.detailForm.detail(this.selectionRows[0])
    },

    // 验证Excel表格式
    beforeUpload(file, fileList) {

      // image/jpeg
      // image/png
      // application/vnd.openxmlformats-officedocument.wordprocessingml.document
      // application/pdf
      // application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

      const isXLSX = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
      if (!isXLSX) {
        this.$message.error('导入文件格式有误,只支持.xlsx格式')
        return false
      }

      this.handleImport(file)
      return false
    },
    // 导入Excel表数据
    handleImport(file) {
      var formData = new FormData()
      formData.append('file', file)
      this.importLoading = true;
      request({
        url: this.Urls.importExcelUrl,
        method: 'post',
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        timeout: 0,
        data: formData
      }).then(res => {
        this.importLoading = false;
        if (res.code == 0) {
          this.$notify.success({
            message: '导入成功'
          })
          this.getList(1)
        } else {
          this.$notify.error({
            message: res.msg
          })
        }
      }).finally(() => {
        this.importLoading = false;
      })
    },
    // 下载模板
    handleDownload() {
      window.open(process.env.VUE_APP_BASE_API + this.Urls.downloadExcelUrl)
    },
    // 更多操作
    handleMenuClick(e) {
      if (this.selectedRowKeys.length == 0) {
        this.$notify.warning({
          message: '请选择你要进行该操作的数据!'
        })
        return
      }
      switch (e.key) {
        case 'download':
          this.handleDownload()
          break;
        case 'del':
          this.handleBatchDel('DISABLE')
      }
      this.selfMenuClick(e)
    },
    selfMenuClick(e) {},

    // 批量导出Excel
    handleExport() {
      let _this = this
      if (_this.list.length == 0) {
        _this.$notify.warning({
          message: '无数据可以导出!'
        })
        return
      }
      this.$confirm('如你点击确认后，请稍等...', '确认导出?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(() => {
        _this.localLoading = true
        _this.downloadLoading = true
        request({
          url: _this.Urls.exportExcelUrl,
          method: 'post',
          data: _this.listQuery.condition,
          responseType: 'blob'
        }).then(res => {
          _this.localLoading = false
          _this.downloadLoading = false
          if (!res) {
            return
          }
          const blob = new Blob([res])
          let fileName = _this.$route.meta.title + _this.fileExt
          if ('download' in document.createElement('a')) {
            // 非IE下载
            const elink = document.createElement('a')
            elink.download = fileName
            elink.style.display = 'none'
            elink.href = URL.createObjectURL(blob)
            document.body.appendChild(elink)
            elink.click()
            URL.revokeObjectURL(elink.href) // 释放URL 对象
            document.body.removeChild(elink)
          } else {
            // IE10+下载
            navigator.msSaveBlob(blob, fileName)
          }
        }).catch(() => {
          _this.localLoading = false
          _this.downloadLoading = false
        })
      }).catch(() => {});
    },

    // 打印pdf
    handlePrint() {
      let _this = this
      if (_this.list.length == 0) {
        _this.$notify.warning({
          message: '无数据可以打印!'
        })
        return
      }
      _this.$confirm({
        title: '确认打印?',
        content: '点击打印后，请等待...',
        onOk() {
          _this.localLoading = true
          request({
            url: _this.Urls.printPdfUrl,
            method: 'post',
            data: _this.listQuery.condition,
            responseType: 'blob'
          }).then(res => {
            _this.localLoading = false
            if (!res) {
              return
            }
            const blob = new Blob([res], {
              type: 'application/pdf'
            })
            let url = URL.createObjectURL(blob)
            window.open(url, '_blank')
          })
        },
        onCancel() {},
      });

    },

    // 文件下载
    handleFileDownload(record) {
      request({
        url: this.Urls.fileIdsUrl + record.id,
        method: 'get'
      }).then(res => {
        if (res.code == 0) {
          let id = res.data
          this.downloadFile(id)
        }
      })
    },
    downloadFile(ids) {
      window.open(process.env.VUE_APP_BASE_API + this.Urls.downloadFileUrl + '?ids=' + ids)
    },
    // 批量文件下载
    handleFileBatchDownload() {
      request({
        url: this.Urls.batchFileIdsUrl,
        method: 'post',
        data: this.selectedRowKeys,
      }).then(res => {
        if (res.code == 0) {
          let ids = res.data.join()
          this.downloadFilel(ids)
        }
      })
    },

    // 地区数据
    getArea(id, data) {
      request({
        url: this.Urls.areaListUrl + id,
        method: 'get'
      }).then(res => {
        if (res.code == 0) {
          this[data] = res.data.records;
        } else {

        }
      })
    },
    handleProvinceChange(val) {
      this.getArea(val, 'cityList')
    },
    handleCityChange(val) {
      this.getArea(val, 'districtList')
    },

    // 查询条件 时间
    handleStartTime(date) {
      this.listQuery.condition.startTime = date
    },
    handleEndTime(date) {
      this.listQuery.condition.endTime = date
    },

    // 表格点击行事件
    rowClick(record, index) {
      return {
        on: {
          click: (e) => {
            e.preventDefault();
            let keys = [],
              rows = [];
            keys.push(record.id)
            rows.push(record)
            this.selectedRowKeys = keys
            this.selectionRows = rows
          },
          contextmenu: (e) => {
            e.preventDefault();
            let keys = [],
              rows = [];
            keys.push(record.id)
            rows.push(record)
            this.selectedRowKeys = keys
            this.selectionRows = rows
            this.menuVisible = true;
            this.menuStyle.top = e.clientY + "px";
            this.menuStyle.left = e.clientX + "px";
            document.addEventListener("click", this.cancelClick);
          }
        }
      }
    },
    cancelClick() {
      this.menuVisible = false
      document.addEventListener("click", this.cancelClick);
    },
    // 刷新列表
    refresh() {
      this.getList(1)
    }
  }
}
export default baseMixin
